/*
 *Api请求后端数据并缓存
 *@author: yczha
 */

import { reactive } from "vue"
import { ApiGetInvNum, ApiGetInvInfoAll, ApiGetInvCheckDetail, ApiGetUserAccount } from "../http/api"
import { ElMessage } from "element-plus"
import { basename } from "./utils"
import store from "../store"

//获取发票数量
const GetInvNum = (callback = null) => {
    ApiGetInvNum().then((res) => {
        if (res.code === 2000) {
            if (res.data.inv_num === store.state.invNum) {
                if (callback !== null) {
                    callback(false);//用来设置加载状态为false
                }
            } else {
                //发票数量有更新，则需要把缓存内容清理掉
                store.commit("clearInvList");
            }
            store.commit("setInvNum", res.data.inv_num);
        } else {
            console.log("读取发票信息出错:", res);
            ElMessage.error("读取发票数量信息出错!");
        }
    });
};


//加载发票数据
const GetInvDataBatch = (callback = null, page = 1) => {
    ApiGetInvInfoAll({ page }).then((res) => {
        if (res.code === 2000) {
            for (let row in res.data) {
                let row_data = res.data[row];
                let invData = reactive({
                    fileName: basename(row_data.storage_path),
                    invTip: "解析失败",
                    invCode: "",
                    invNum: "",
                    invDate: "",
                    invMoney: "",
                    invChk: "",
                    status: false,
                    code: "",
                });
                if (row_data.status) {
                    invData["invTip"] = "解析成功";
                    invData["invCode"] = row_data.inv_code;
                    invData["invNum"] = row_data.inv_num;
                    invData["invDate"] = row_data.inv_date;
                    invData["invMoney"] = row_data.inv_money || "";
                    invData["invChk"] = row_data.inv_chk.toString();
                    invData["status"] = row_data.status;
                    if (row_data.detail) {
                        try {
                            const detail = JSON.parse(row_data.detail);
                            for (let cat in detail) {
                                if (cat == "raw") continue;
                                for (let key in detail[cat]) {
                                    let vals = detail[cat][key];
                                    if (cat == "commodity") {
                                        vals = "";
                                        for (let idx in detail[cat][key]) {
                                            vals = vals + detail[cat][key][idx].word + "\n";
                                        }
                                    }
                                    invData[key] = vals;
                                }
                            }
                            invData["invTip"] = "全票面解析成功";
                        } catch (err) {
                            ElMessage.error("解析详情出错!");
                        }
                    }
                }
                // console.log("invData", invData)
                store.commit("appendInvListRow", invData);
                // if (row_data.status) {
                //     GetInvCheckData(invData.invCode, invData.invNum);
                // }
            }
            if (store.state.invList.length < store.state.invNum) {
                GetInvDataBatch(callback, page + 1);
            } else {
                if (callback !== null)
                    callback(false);
            }
        } else {
            ElMessage.error(res.message);
        }
    });
};

//获取查验结果
const GetInvCheckData = (invCode, invNum, callback = null, interval = null) => {
    store.commit("updateInvListVal", [invCode, invNum, 'loading', true])
    if (callback !== null) callback('loading', true)
    ApiGetInvCheckDetail({
        inv_code: invCode,
        inv_num: invNum,
    }).then((res) => {
        if (res && res.code === 2000) {
            store.commit("updateInvListRow", {
                ...res.data.info,
                url: res.data.screenshot,
                invCode: res.data.inv_code,
                invNum: res.data.inv_num,
                invChk: res.data.info["校验码"],
                invMoney: res.data.info["合计金额"],
                invTip: "查验成功"
            })
            if (callback !== null) callback('invTip', '查验成功')

            if (interval) {
                //更新账户余额
                ApiGetUserAccount().then((res) => {
                    if (res && res.code === 2000) store.commit("setUserAmount", res.data.amount);
                });
                clearInterval(interval)
            }
        } else if (res && res.code === 5008) {
            store.commit("updateInvListVal", [invCode, invNum, 'invTip', res.message]);
            if (interval) clearInterval(interval)
        }
        store.commit("updateInvListVal", [invCode, invNum, 'loading', false]);
        if (callback !== null) callback('loading', false)
        // if (res) console.log("查验状态:", invCode, invNum, res.code, res.message)
    });
};

//指定时间内多次查验
const LoopGetInvCheckData = (invCode, invNum, callback = null, timeout = 30, timestep = 3) => {
    let count = 0;
    let interval = setInterval(() => {
        GetInvCheckData(invCode, invNum, callback, interval);
        if (count > timeout / timestep) {
            clearInterval(interval);
            store.commit("updateInvListVal", [invCode, invNum, 'invTip', '查询超时!'])
            if (callback !== null) callback('invTip', '查询超时!')
        } else {
            const invTip = `正在查验${count.toString().padStart(2, "0")}`;
            store.commit("updateInvListVal", [invCode, invNum, 'invTip', invTip])
            if (callback !== null) callback('invTip', invTip)
            count += 1;
        }
    }, timestep * 1000);
};


export { GetInvNum, GetInvDataBatch, GetInvCheckData, LoopGetInvCheckData }